package example.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class APIUtil {
    static public void ok(HttpServletResponse response, Object obj) throws IOException {
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(JSON.toJSONString(obj));
    }

    static public void fail(HttpServletResponse response, String msg) throws IOException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg", msg);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(jsonObject.toString());
    }

    static public void error(HttpServletResponse response, String msg) throws IOException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg", msg);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(jsonObject.toString());
    }
}
